package our.pack;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class MediaAudioActivity extends Activity{

	private ImageView microphone;
	private TextView recordingLabel;
	private MediaRecorder recorder;
	private MetaDataDataSource metaDataDatasource;
	private static final File PATH = Environment.getExternalStorageDirectory();
	private String fullNamePath;
	private MyPoint point;
	private static int id = 1;
	private Boolean recording = false;
	
	/**
	 * In this class you can record a audio file and makes a tempfile
	 */
	public void onCreate(Bundle SaveInstanceState){
		super.onCreate(SaveInstanceState);
		setContentView(R.layout.mediaaudio);
		recordingLabel = (TextView) findViewById(R.id.recordingLabel);

		//db
		metaDataDatasource = new MetaDataDataSource(this);
		metaDataDatasource.open();
		
		//get tthe point where it's made
		Intent i = getIntent();
		Bundle b = i.getExtras();
		point = (MyPoint) b.get("Point");
		
		//make id
		id = (int) (metaDataDatasource.getLatestId() + 1); 
		
		//initialize the recorder
		recorder = new MediaRecorder();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setMaxDuration(3600000); //1 uur
		recorder.setMaxFileSize(1048576); //ong 1mb
		
		//set the outputfile
		File file = new File(PATH + "/Sound" + id + ".3GP");
		fullNamePath = PATH + "/Sound" + id + ".3GP";
		recorder.setOutputFile(fullNamePath);
		Log.d("Audio Record", "Make File: " + fullNamePath);
		
		//get the "button" and set the listener
		microphone = (ImageView) findViewById(R.id.microphone);
		microphone.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				if(recording){
					recorder.stop();
					recorder.release();
					recordingLabel.setText("Not Recording");
					// save it here
					
					Intent i = new Intent(MediaAudioActivity.this, MediaAudioSaveActivity.class);
					i.putExtra("PATH",fullNamePath);
					i.putExtra("Point", point);
					startActivity(i);
					
					finish();
					
				}else {
						
					//start the recorder
					try {
						recorder.prepare();
						recorder.start();
						recordingLabel.setText("Recording");
						recording = true;
						
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	
					
				
				}
			}
		});
	}
}
